package tool

import (
	"encoding/json"
	"fmt"
	"github.com/garyburd/redigo/redis"
)

func NewConn() redis.Conn {
	conn, err := redis.Dial("tcp", "127.0.0.1:6379")
	if err != nil {
		fmt.Println(err)
	}

	return conn
}

////结构体存入redis
func WriteToRedis(u []Upgrade) {

	conn := NewConn()
	defer conn.Close()

	var ub []byte
	ub, err := json.Marshal(u)
	if err != nil {
		fmt.Printf("%s\n", err.Error())
	}
	conn.Send("SET", "upgrade", ub)
	conn.Flush()
	v, err := conn.Receive()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(v)

	for k, v1 := range u {
		str := fmt.Sprintf("upgrade2:%d", k)
		_, err := conn.Do("HMSET", redis.Args{str}.AddFlat(v1)...)
		if err != nil {
			fmt.Println(err)
		}
	}
}

//集合存入redis
func WriteToRedis2(m []map[string]map[string]string) {
	conn := NewConn()
	defer conn.Close()
	var ub []byte
	ub, err := json.Marshal(m)
	if err != nil {
		fmt.Println(err)
	}
	v,err := conn.Do("LPUSH", "xlsx_map",string(ub))
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(v)

}

//获取结构体
func GetStruct() (u []Upgrade) {
	conn := NewConn()
	defer conn.Close()
	conn.Send("GET", "upgrade")
	conn.Flush()
	ub, err := redis.Bytes(conn.Receive())
	if err != nil {
		fmt.Println(err)
	}
	err = json.Unmarshal(ub, &u)
	if err != nil {
		fmt.Println(err)
	}
	return
}

//获取结构体2
func GetStruct2(k int) (u Upgrade) {
	conn := NewConn()
	defer conn.Close()
	var err error
	str := fmt.Sprintf("upgrade2:%d", k)
	u.Level, err = redis.Int(conn.Do("HGET", str, "level"))
	if err != nil {
		fmt.Println("1", err)
		return
	}
	u.Exp, err = redis.Int(conn.Do("HGET", "upgrade2:2", "exp"))
	if err != nil {
		fmt.Println("2", err)
		return
	}
	r, err := redis.String(conn.Do("HGET", "upgrade2:2", "cost"))
	if err != nil {
		fmt.Println("3", err)
		return
	}
	u.Cost, err = StoInts(r)
	if err != nil {
		fmt.Println("3", err)
		return
	}
	return
}

//获取map
func GetMap() (m []map[string]map[string]string) {
	conn := NewConn()
	defer conn.Close()
	ub, err := redis.String(conn.Do("LPOP", "xlsx_map"))
	if err != nil {
		fmt.Println(err)
	}
	err = json.Unmarshal([]byte(ub), &m)
	if err != nil {
		fmt.Println(err)
	}
	return
}
